<template>
  <div class="page-container">
    <header class="header">
      <div class="header-content">
        <router-link to="/" class="logo">
          <h1>匿名社交网络系统</h1>
        </router-link>
        <div class="user-info">
          <el-dropdown @command="handleCommand">
            <div class="user-dropdown">
              <el-avatar :size="32" :src="userStore.userInfo?.avatar">
                {{ userStore.userInfo?.nickname?.[0] || userStore.userInfo?.username?.[0] }}
              </el-avatar>
              <span class="username">{{ userStore.userInfo?.nickname || userStore.userInfo?.username }}</span>
              <el-icon><arrow-down /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'ADMIN'" command="dashboard">
                  <el-icon><Odometer /></el-icon>仪表盘
                </el-dropdown-item>
                <el-dropdown-item v-if="userStore.userInfo?.role === 'ADMIN'" command="k-anonymity">
                  <el-icon><Setting /></el-icon>K匿名配置
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><switch-button /></el-icon>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </header>

    <main class="main-content">
      <div class="content-wrapper">
        <el-card class="config-card">
          <template #header>
            <div class="card-header">
              <h2 class="card-title">K匿名配置管理</h2>
              <el-button type="primary" @click="showCreateDialog">
                新建配置
              </el-button>
            </div>
          </template>

          <el-table :data="configs" style="width: 100%">
            <el-table-column prop="kvalue" label="K值" width="100" />
            <el-table-column prop="strategy" label="匿名化策略" width="150" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="enabled" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.enabled ? 'success' : 'info'">
                  {{ row.enabled ? '已启用' : '已禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250" fixed="right">
              <template #default="{ row }">
                <el-button
                  v-if="!row.enabled"
                  type="success"
                  size="small"
                  @click="handleToggle(row)"
                >
                  启用
                </el-button>
                <el-button
                  v-else
                  type="info"
                  size="small"
                  @click="handleToggle(row)"
                >
                  禁用
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  @click="handleEdit(row)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </main>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑配置' : '新建配置'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="K值" prop="kvalue">
          <el-input-number
            v-model="form.kvalue"
            :min="2"
            :max="100"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="匿名化策略" prop="strategy">
          <el-select v-model="form.strategy" placeholder="请选择匿名化策略">
            <el-option label="基础策略" value="BASIC" />
            <el-option label="增强策略" value="ENHANCED" />
            <el-option label="严格策略" value="STRICT" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入配置描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="enabled">
          <el-switch v-model="form.enabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowDown,
  Odometer,
  Setting,
  SwitchButton
} from '@element-plus/icons-vue'
import {
  getKAnonymityConfigs,
  createKAnonymityConfig,
  updateKAnonymityConfig,
  toggleKAnonymityConfig,
  deleteKAnonymityConfig
} from '../api'

const router = useRouter()
const userStore = useUserStore()
const configs = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const form = ref({
  kvalue: 2,
  strategy: 'BASIC',
  description: '',
  enabled: true
})

const rules = {
  kvalue: [
    { required: true, message: '请输入K值', trigger: 'blur' },
    { type: 'number', min: 2, message: 'K值必须大于等于2', trigger: 'blur' }
  ],
  strategy: [
    { required: true, message: '请选择匿名化策略', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入配置描述', trigger: 'blur' }
  ]
}

const fetchConfigs = async () => {
  try {
    const response = await getKAnonymityConfigs()
    configs.value = response.data
  } catch (error) {
    ElMessage.error('获取配置列表失败')
  }
}

const showCreateDialog = () => {
  isEdit.value = false
  form.value = {
    kvalue: 2,
    strategy: 'BASIC',
    description: '',
    enabled: true
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      await updateKAnonymityConfig(form.value)
      ElMessage.success('更新成功')
    } else {
      await createKAnonymityConfig(form.value)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchConfigs()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

const handleToggle = async (row) => {
  try {
    await toggleKAnonymityConfig(row.id, !row.enabled)
    ElMessage.success(row.enabled ? '已禁用' : '已启用')
    fetchConfigs()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该配置吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteKAnonymityConfig(row.id)
    ElMessage.success('删除成功')
    fetchConfigs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

const handleCommand = (command) => {
  switch (command) {
    case 'dashboard':
      router.push('/admin/dashboard')
      break
    case 'k-anonymity':
      router.push('/admin/k-anonymity')
      break
    case 'logout':
      userStore.logout()
      router.push('/login')
      break
  }
}

onMounted(() => {
  fetchConfigs()
})
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  height: 100%;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  text-decoration: none;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  color: var(--primary-color);
}

.user-info {
  display: flex;
  align-items: center;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-dropdown:hover {
  background-color: var(--background-color);
}

.username {
  margin: 0 8px;
  color: var(--text-color);
}

.main-content {
  padding-top: 80px;
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.config-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  margin: 0;
  font-size: 18px;
  color: var(--text-color);
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 5px;
}

@media screen and (max-width: 768px) {
  .content-wrapper {
    padding: 0 10px;
  }
}
</style> 